package ad.android.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;

import ad.android.dao.IAdDao;
import ad.android.dao.base.BaseDao;
import ad.android.dto.cond.AdCondition;
import ad.android.dto.cond.SearchCondition;
import ad.android.exception.DaoException;
import ad.android.model.Ad;

public class AdDaoHibernateImpl extends BaseDao implements IAdDao{

	@Override
	public Ad findAdById(Long id) {
		try {
			Ad ad = (Ad) get(Ad.class, id);
			return ad;
		} catch (DataAccessException e) {
			logDebug("findAdById", e);
			throw new DaoException(e);
		}
	}

	@Override
	public int findAdNumByWeight(int intWeight) throws DaoException {
		try {
			String hql = "select count(_ad.id) from Ad as _ad where _ad.adWeight=:adWeight";
			Session session = getSessionFactory().getCurrentSession();
			Query query = session.createQuery(hql);
			
			query.setInteger("adWeight", intWeight);
			Long num = (Long)query.uniqueResult();
			return num.intValue();
		} catch (HibernateException e) {
			log.debug("findAdNumByWeight",e);
			throw new DaoException(e);
		}
	}

	@Override
	public List<Ad> findAdByCondition(AdCondition cond, SearchCondition sCond)
			throws DaoException {
		try {
			String hql = "from Ad as _ad where 1=1";
			if( cond != null){
				hql += " and _ad.adWeight=:adWeight";
			}
			Session session = getSessionFactory().getCurrentSession();
			Query query = session.createQuery(hql);
			
			if( cond!= null){
				query.setInteger("adWeight", cond.getWeigth());
			}
			
			if( sCond != null){
				query.setFirstResult(sCond.getStart());
				query.setMaxResults(sCond.getLimit());
			}
			
			List<Ad> adList = query.list();
			
			return adList;
		} catch (HibernateException e) {
			log.debug("findAdByCondition",e);
			throw new DaoException(e);
		}
	}
	
}
